package com.dean.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

/**
 * @ClassName SqlWriteUtils
 * @Description sql写入工具类
 * @Author dean
 * @Date 2021/11/30 15:40
 */
public class TxtWriteUtils {
    private final static Logger logger = LoggerFactory.getLogger(TxtWriteUtils.class);

    /**
     * 默认返回"OK",其他字段为报错信息
     * 使用BufferWriter泪写文本文件
     */
    public static String writeTxt(String fileName,String [] head,String [][] datas){
        FileWriter fileWriter = null;
        BufferedWriter bufferedWriter = null;
        try{
            fileWriter = new FileWriter(fileName);
            bufferedWriter = new BufferedWriter(fileWriter);
            String fieldStr = StringUtils.arrayToString(head);
            String preSql = "insert into table_name("+fieldStr+")values(";
            String endSql = ");";
            int i=1;
            for (String[] data : datas) {
                String valueStr =StringUtils.arrayToSqlVals(data);
                bufferedWriter.append(preSql);
                bufferedWriter.append(valueStr);
                bufferedWriter.append(endSql);
                if(i< datas.length){
                    bufferedWriter.newLine();
                }
                i++;
            }
        }catch(IOException e){
            logger.error(e.getMessage(),e);
            return e.getMessage();
        }finally {
            if(bufferedWriter !=null){
                try {
                    bufferedWriter.flush();
                    bufferedWriter.close();
                } catch (IOException e) {
                    logger.error(e.getMessage(),e);
                    return e.getMessage();
                }
            }
            if(fileWriter!= null){
                try {
                    fileWriter.close();
                } catch (IOException e) {
                    logger.error(e.getMessage(),e);
                    return e.getMessage();
                }
            }

        }
        return "OK";
    }
}
